package com.newshub.app.ui.news

import android.util.Log
import androidx.lifecycle.LiveData
import androidx.lifecycle.MutableLiveData
import androidx.lifecycle.ViewModel
import androidx.lifecycle.viewModelScope
import com.newshub.app.data.model.News
import com.newshub.app.data.repository.NewsRepository
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.launch
import kotlinx.coroutines.withContext

class NewsViewModel : ViewModel() {
    
    private val repository = NewsRepository
    
    // 新闻详情
    private val _newsDetail = MutableLiveData<News?>()
    val newsDetail: LiveData<News?> = _newsDetail
    
    // 新闻列表
    private val _newsList = MutableLiveData<List<News>>()
    val newsList: LiveData<List<News>> = _newsList
    
    // 加载状态
    private val _isLoading = MutableLiveData<Boolean>()
    val isLoading: LiveData<Boolean> = _isLoading
    
    // 错误信息
    private val _errorMessage = MutableLiveData<String?>()
    val errorMessage: LiveData<String?> = _errorMessage
    
    // 收藏状态
    private val _isFavorite = MutableLiveData<Boolean>()
    val isFavorite: LiveData<Boolean> = _isFavorite
    
    /**
     * 加载新闻详情
     */
    fun loadNewsDetail(newsId: String) {
        viewModelScope.launch(Dispatchers.IO) { // 在IO线程执行耗时操作
            try {
                withContext(Dispatchers.Main) {
                    _isLoading.value = true
                    _errorMessage.value = null
                }
                
                // 获取新闻详情
                val newsDetail = repository.getNewsDetailSync(newsId)
                
                // 获取新闻列表，找到对应的新闻项
                val newsList = repository.createMockNewsList()
                val news = newsList.find { it.docid == newsId }
                
                // 在主线程更新UI数据
                withContext(Dispatchers.Main) {
                    if (news != null) {
                        // 将NewsDetail的body内容合并到News对象中
                        val updatedNews = news.copy(
                            title = newsDetail?.title ?: news.title,
                            source = newsDetail?.source ?: news.source,
                            ptime = newsDetail?.ptime ?: news.ptime
                        )
                        _newsDetail.value = updatedNews
                    } else {
                        _newsDetail.value = null
                        _errorMessage.value = "未找到新闻详情"
                    }
                }
            } catch (e: Exception) {
                Log.e("NewsViewModel", "加载新闻详情异常", e)
                withContext(Dispatchers.Main) {
                    _errorMessage.value = "加载新闻详情失败"
                }
            } finally {
                withContext(Dispatchers.Main) {
                    _isLoading.value = false
                }
            }
        }
    }
    
    /**
     * 加载分类新闻
     */
    fun loadCategoryNews(category: String) {
        viewModelScope.launch(Dispatchers.IO) {
            try {
                withContext(Dispatchers.Main) {
                    _isLoading.value = true
                    _errorMessage.value = null
                }
                
                // 获取所有新闻，然后根据分类筛选
                val allNews = repository.createMockNewsList()
                val filteredNews = if (category == "推荐") {
                    allNews
                } else {
                    allNews.filter { it.category == category }
                }
                
                withContext(Dispatchers.Main) {
                    _newsList.value = filteredNews
                }
            } catch (e: Exception) {
                Log.e("NewsViewModel", "加载分类新闻异常", e)
                withContext(Dispatchers.Main) {
                    _errorMessage.value = "加载分类新闻失败"
                }
            } finally {
                withContext(Dispatchers.Main) {
                    _isLoading.value = false
                }
            }
        }
    }
    
    /**
     * 切换收藏状态（基于新闻ID）
     */
    fun toggleFavorite(newsId: String) {
        viewModelScope.launch(Dispatchers.Main) { // 这个操作主要是UI更新，可以在主线程执行
            try {
                // 获取当前新闻详情
                val currentNews = _newsDetail.value
                if (currentNews != null && currentNews.docid == newsId) {
                    // 更新当前新闻的收藏状态
                    val updatedNews = currentNews.copy(isFavorite = !currentNews.isFavorite)
                    _newsDetail.value = updatedNews
                }
                
                // 更新新闻列表中的收藏状态
                val currentList = _newsList.value ?: emptyList()
                val updatedList = currentList.map { news ->
                    if (news.docid == newsId) {
                        news.copy(isFavorite = !news.isFavorite)
                    } else {
                        news
                    }
                }
                _newsList.value = updatedList
                
                // 调用repository更新收藏状态
                repository.toggleFavorite(newsId)
            } catch (e: Exception) {
                Log.e("NewsViewModel", "切换收藏状态异常", e)
                _errorMessage.value = "切换收藏状态失败"
            }
        }
    }
    
    /**
     * 切换收藏状态（基于News对象）
     */
    fun toggleFavorite(news: News) {
        toggleFavorite(news.docid)
    }
}